package cs5226.interceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;

import cs5226.util.*;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class LoginInterceptor implements Interceptor  {

	private static final long serialVersionUID = 1L;
	public String intercept (ActionInvocation invocation) throws Exception {
 
	    final ActionContext context = invocation.getInvocationContext ();
	    HttpServletRequest request = (HttpServletRequest) context.get(ServletActionContext.HTTP_REQUEST);
	    HttpSession session =  request.getSession (true);

	    Object loggedIn = session.getAttribute ("loggedIn");
	    
	    if (loggedIn == null) {
	        String loginAttempt = request.getParameter ("loginAttempt");

	        
	        if("Y".equalsIgnoreCase(loginAttempt))  {
	        	String userid = request.getParameter("userid");
				String pwd = request.getParameter("pwd");
	            if (processLoginAttempt (userid, pwd) ) {
	            	session.setAttribute ("loggedIn", userid);
	                return "login-success";
	            } else {
	            	request.setAttribute("msg", "Login failed due to invalid user name/password.");
	            	return "login-error";
	            }
	        }else{
	    		request.setAttribute("msg", "You haven't logged in yet, please login here.");
				return "login-error";
	        }
	    } else {
	        return invocation.invoke ();
	    }
	}
	
	private boolean processLoginAttempt(String userid, String pwd) throws Exception {
		
		boolean isAuthenticated = false;
	
		try {
			if(!StringUtil.isNullOrBlank(userid) && Constants.USER_ID.equalsIgnoreCase(userid.trim()) && Constants.PASSWORD.equals(pwd)){
				isAuthenticated = true;
			}
					
		} catch (Exception e) {
			e.printStackTrace();
		}
	
		return isAuthenticated;
	}
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void init() {
		// TODO Auto-generated method stub
		
	}
	
	

}